package com.xd.springboot.interceptor;

import com.xd.springboot.annotation.UnInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class MyInterceptor implements HandlerInterceptor {
    private static  final Logger log= LoggerFactory.getLogger(MyInterceptor.class);
    //url匹配到Controller中的某个方法，在执行Handler之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod= (HandlerMethod) handler;
        Method method =handlerMethod.getMethod();
        String methodName = method.getName();
        log.info("---------拦截到了方法：{}",methodName);
        //添加了自定义注解 UnInterceptor的方法不用拦截
        UnInterceptor unInterceptor=method.getAnnotation(UnInterceptor.class);
        if(null!=unInterceptor)
        {
            return true;
        }
        //判断用户是否登录
        String token =request.getParameter("token");
        if(null == token || "".equals(token))
        {
            log.info("用户未登录，执行执行权限，请先登录...");
            return false;
        }
        //返回true才会执行，返回false会取消当前执行
        return true;
    }

    //Handle执行后执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("方法执行完之后调用，测试视图渲染器还没有执行");
    }

    //视图渲染器执行前执行， 要求 preHandle返回值为true
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("视图渲染器之前执行");
    }
}
